package com.lu.library.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

abstract class BaseViewModel<UiState:IUiState,UiIntent:IUiIntent> :ViewModel(){



    private val _uiStateFlow = MutableStateFlow(initUiState())
    val uiStateFlow: StateFlow<UiState> = _uiStateFlow.asStateFlow()

    private val _uiIntentFlow: Channel<UiIntent> = Channel()
    private val uiIntentFlow: Flow<UiIntent> = _uiIntentFlow.receiveAsFlow()

    protected abstract fun initUiState():UiState

    /**
     * 发送意图
     */
    fun sendUiIntent(uiIntent: UiIntent){
        viewModelScope.launch {
            _uiIntentFlow.send(uiIntent)
        }
    }

    protected fun updateUiState(copy:UiState.()->UiState){
        _uiStateFlow.update{copy(_uiStateFlow.value)}
    }

    init {
        viewModelScope.launch {
            uiIntentFlow.collect{
                handleIntent(it)
            }
        }
    }
    protected abstract fun handleIntent(intent: UiIntent)

}